package com.fysports.web.config.asyn;

import com.jfinal.log.Log;
import com.fysports.web.kit.cache.EHCacheFactory;
import com.fysports.web.kit.commons.DateTimeKit;
import com.fysports.web.model.system.SystemDict;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;


/**
 * 异步加载缓存并且定时更新
 * Created by konbluesky
 * Date : 14-8-21 下午3:10
 * Project : JdmData_WebServer
 */
public class AsynInitParamCache {

    private static Log log = Log.getLog(AsynInitParamCache.class);
    /**
     * 定时任务对象
     */
    private static Timer timer = new Timer();


    public static void start() {
        log.debug("AsynInitParamCache-启动-timer");
        // 6.缓存字典
        timer.schedule(new TimerTask() {
            @Override public void run() {
                log.debug("缓存参数初始化 start ...");
                pingtai_cacheDict();
                log.debug("缓存参数初始化 end ...");
            }
        }, 1000, DateTimeKit.time_minutes * 1000 * 10);// 启动项目一秒后执行，然后每次间隔5分钟
    }


    /**
     * 停止任务
     */
    public static void stop() {
        if (null != timer) {
            log.debug("AsynInitParamCache-cancel-timer");
            timer.cancel();
            log.debug("AsynInitParamCache-cancel-timer-success!");
        }
        else {
            log.debug("AsynInitParamCache-cancel-timer-Fail!");
        }
    }


    /**
     * 缓存业务字典
     *
     * @author 董华健    2012-10-16 下午1:17:04
     */
    public static void pingtai_cacheDict() {
        EHCacheFactory cacheFactory = EHCacheFactory.getInstance();
        List<SystemDict> dictList = SystemDict.dao.search(SystemDict.COL_LIVEFLAG, "1");
        for (SystemDict dict : dictList) {
            cacheFactory.add(EHCacheFactory.cache_name_system, dict.getStr("name"), dict);
            dict = null;
        }
        dictList = null;
    }


    public static void refresh() {
        pingtai_cacheDict();
    }
}
